package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.FastOrderListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean.OrderBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.TextChange;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Descriptions：快速下单以及常用收发货信息界面
 * <p>
 * Author：ChenME
 * Date：2017/1/7
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_fast_order)
public class FastOrder_CommSendOrPickUpInfo_Activity extends AppBaseActivity {

    @ViewById(R.id.listView)
    ListView listView;

    @ViewById(R.id.rl_add)
    RelativeLayout rl_add;

    @ViewById(R.id.include_title)
    RelativeLayout include_title;//正常的Title
    @ViewById(R.id.rl_searchTitle)
    RelativeLayout rl_searchTitle;//含有搜索框的标题栏
    @ViewById(R.id.iv_backBtn)
    ImageView iv_backBtn;//搜索标题的返回按钮
    @ViewById(R.id.tv_searchBtn)
    TextView tv_searchBtn;//搜索按钮

    @Extra("whichPage")
    int whichPage;

    public static final int Result_CompleteOrderChose = 0x2312;//完成快速下单的选择
    public static final int Page_FastOrder = 0x2313;//快速下单
    public static final int Page_CommFromInfo = 0x2314;//常用发货信息
    public static final int Page_CommToInfo = 0x2315;//常用收货信息

    private final int Request_AddOrEditInfo = 0x2001;//添加编辑常用信息

    private List<OrderBean> dataList;
    private FastOrderListAdapter mAdapter;

    private FastOrder_CommSendOrPickUpInfo_Activity mActivity;

    private String inputKeyWord = "";//收入框总的文字

    @AfterViews
    void onPageStart() {
        mActivity = this;

        dataList = new ArrayList<>();
        switch (whichPage) {
            case Page_FastOrder:
//                setDefaultTitle(this, R.string.string_commSendOrPickUp_fastOrderTitle);
                iv_backBtn.setOnClickListener(view -> {
                    finish();
                    animUtils.leftOutAnimation(mActivity);
                });
                mAdapter = new FastOrderListAdapter(this, dataList, 3);

                // 在下单历史记录页面，暂时隐藏根据手机号匹配历史订单的功能；
//                include_title.setVisibility(View.GONE);
//                rl_searchTitle.setVisibility(View.VISIBLE);
                setDefaultTitle(this, "快速下单");
                break;

            case Page_CommFromInfo:
                setDefaultTitle(this, R.string.string_commSendOrPickUp_sendTitle);
                mAdapter = new FastOrderListAdapter(this, dataList, 2);
                rl_add.setVisibility(View.VISIBLE);
                break;

            case Page_CommToInfo:
                setDefaultTitle(this, R.string.string_commSendOrPickUp_pickUpTitle);
                mAdapter = new FastOrderListAdapter(this, dataList, 1);
                rl_add.setVisibility(View.VISIBLE);
                break;
        }

        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent();
            intent.putExtra("orderBean", (Parcelable) dataList.get(position));
            setResult(Result_CompleteOrderChose, intent);
            onBackPressed();
        });

        if (Page_CommFromInfo == whichPage || Page_CommToInfo == whichPage) {
            listView.setOnItemLongClickListener((parent, view, position, id) -> {
                showManageDialog(dataList.get(position));
                return true;
            });
        }

        loadFastOrderList(true);
    }

    /**
     * 输入框中的内容发生改变时触发
     *
     * @param text
     * @param tv
     * @param before
     * @param start
     * @param count
     */
    @TextChange(R.id.et_searchInput)
    void onSearchInputChanged(CharSequence text, TextView tv, int before, int start, int count) {
        inputKeyWord = text.toString().trim();
        if (inputKeyWord.length() > 0) {
            tv_searchBtn.setEnabled(true);
            tv_searchBtn.setTextColor(getResources().getColor(R.color.color_defaultTextDark));
        } else {
            tv_searchBtn.setEnabled(false);
            tv_searchBtn.setTextColor(getResources().getColor(R.color.color_defaultTextLight));
        }
    }

    /**
     * 搜索按钮的点击事件
     */
    @Click(R.id.tv_searchBtn)
    void onSearchClick() {

    }

    /**
     * 显示管理对话框
     *
     * @param bean
     */
    private void showManageDialog(OrderBean bean) {

        String[] items = new String[]{getString(R.string.string_commSendOrPickUp_manageMenuEdit),
                getString(R.string.string_commSendOrPickUp_manageMenuDel)};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog dialog = builder
                .setItems(items, (dialog1, which) -> {
                    if (0 == which) {
                        if (Page_CommFromInfo == whichPage) {//常用发货信息
                            EditSendOrPickUpInfoActivity_.intent(this)
                                    .whichPage(EditSendOrPickUpInfoActivity.Page_CommFromInfoList)
                                    .orderBean(bean)
                                    .startForResult(Request_AddOrEditInfo);
                        } else if (Page_CommToInfo == whichPage) {//常用收货信息
                            EditSendOrPickUpInfoActivity_.intent(this)
                                    .whichPage(EditSendOrPickUpInfoActivity.Page_CommToInfoList)
                                    .orderBean(bean)
                                    .startForResult(Request_AddOrEditInfo);
                        }
                        animUtils.leftInAnimation(FastOrder_CommSendOrPickUpInfo_Activity.this);
                    } else {
                        delCommSendOrPickUpInfo(bean.getId());
                    }
                    dialog1.dismiss();
                }).create();
        dialog.show();
    }

    /**
     * 添加编辑常用信息成功
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Request_AddOrEditInfo)
    void onAddOrEditInfoSuccessfulResult(int resultCode, Intent data) {
        if (Value.ResultCode_Comm == resultCode) {
            loadFastOrderList(true);
        }
    }

    /**
     * 删除常用信息
     *
     * @param infoId
     */
    private void delCommSendOrPickUpInfo(String infoId) {
        OrderBean requestBean = new OrderBean();
        requestBean.setId(infoId);

        String requestJson = JsonUtils.createJsonString(requestBean);
        LogUtils.log("测试的" + requestJson);
        try {
            String requestAes = JsonUtils.aes(requestJson);
            callNet(this, InterfaceNet.Net_DelCommSendOrPickUpInfo, requestAes,
                    new NetResultOperate() {
                        @Override
                        public void onSuccess(String content) {
                            App.toast("删除成功！");
                            loadFastOrderList(true);
                        }

                        @Override
                        public void onDataEmpty(String content) {
                        }

                        @Override
                        public void onDataEnd(String content) {
                        }

                        @Override
                        public void onErr(String errorCode, String errorMsg, Context mContext) {
                            super.onErr(errorCode, errorMsg, mContext);

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载订单列表
     */
    private void loadFastOrderList(boolean isClear) {
        String url;
        OrderBean requestBean = new OrderBean();
        requestBean.setS_i("0");
        requestBean.setCount("45");

        if (Page_FastOrder == whichPage) {
            url = InterfaceNet.Net_GetFastOrderList;
        } else {
            url = InterfaceNet.Net_GetCommSendOrPickUpInfoList;
            if (Page_CommFromInfo == whichPage) {
                requestBean.setType("1");
            } else {
                requestBean.setType("2");
            }
        }

        String requestJson = JsonUtils.createJsonString(requestBean);
        try {
            String requestAes = JsonUtils.aes(requestJson);
            callNet(this, url, requestAes, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    if (!StringUtils.isEmpty(content)) {

                        Object obj = JsonUtils.parseJsonString(content, OrderBean.class);
                        if (obj instanceof OrderBean) {
                            OrderBean bean = (OrderBean) obj;
                            if (isClear) {
                                dataList.clear();
                            }
                            dataList.addAll(bean.infolist);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                    dataList.clear();
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onDataEnd(String content) {
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加新的常用信息
     */
    @Click(R.id.btn_add)
    void onAddClick() {
        if (Page_CommFromInfo == whichPage) {//常用发货信息
            EditSendOrPickUpInfoActivity_.intent(this)
                    .whichPage(EditSendOrPickUpInfoActivity.Page_CommFromInfoList)
                    .startForResult(Request_AddOrEditInfo);
        } else if (Page_CommToInfo == whichPage) {//常用收货信息
            EditSendOrPickUpInfoActivity_.intent(this)
                    .whichPage(EditSendOrPickUpInfoActivity.Page_CommToInfoList)
                    .startForResult(Request_AddOrEditInfo);
        }
        animUtils.leftInAnimation(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.leftOutAnimation(this);
    }
}